const express = require('express');
const router = express.Router();
const Message = require('../utils/message')
const pool = require('../utils/connection')

router.get('/findAll', (req, res) => {
  const sql = 'select * from tab_student;'
  pool.getConnection((err, connection) => {
    if (err) throw err;
    connection.query(sql, function (error, results, fields) {
      if (error) throw error;
      connection.release()
      res.json(new Message(200, '查询成功', results))
    });
  })
})

router.get('/pageQuery', (req, res) => {
  let page = req.query.page
  let pageSize = req.query.pageSize
  const sql = `select * from tab_student limit ${(page - 1) * pageSize},${pageSize};`
  pool.getConnection((err, connection) => {
    if (err) throw err;
    connection.query(sql, function (error, results, fields) {
      if (error) throw error;
      connection.release()
      res.json(new Message(200, '查询成功', results))
    });
  })
})

router.post('/saveOrUpdate', (req, res) => {
  let sql = `insert into tab_student(name,gender,birth) values('${req.body.name}','${req.body.gender}',${req.body.birth});`
  if (req.body.id) {
    sql = `update tab_student set name='${req.body.name}',gender='${req.body.gender}',birth=${req.body.birth} where id = ${req.body.id};`
  }
  pool.getConnection((err, connection) => {
    if (err) throw err;
    connection.query(sql, function (error, results, fields) {
      if (error) throw error;
      connection.release()
      res.json(new Message(200, '保存成功'))
    });
  })
})

router.delete('/deleteById', (req, res) => {
  let id = req.query.id
  let sql = `delete from tab_student where id = ${id};`
  pool.getConnection((err, connection) => {
    if (err) throw err;
    connection.query(sql, (error) => {
      if (error) throw error;
      connection.release();
      res.json(new Message(200, '删除成功'))
    })
  })
})

module.exports = router